package com.laxia.config;

import com.laxia.util.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author weishuai
 */
@Configuration
@AllArgsConstructor
public class DateConvertConfig {

    private RequestMappingHandlerAdapter handlerAdapter;

    @PostConstruct
    public void initConverter() {
        ConversionService conversionService = ((ConfigurableWebBindingInitializer) Objects.requireNonNull(handlerAdapter.getWebBindingInitializer())).getConversionService();
        if (conversionService != null) {
            ((GenericConversionService) conversionService).addConverter(new StringToDateConverter());
        }
    }


    public static class StringToDateConverter implements Converter<String, Date> {

        private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        private static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";

        @Override
        public Date convert(@NonNull String source) {
            try {
                if (StringUtil.isNumber(source)) {
                    return new Date(Long.parseLong(source));
                } else if (source.contains("-") && source.length() == 10) {
                    return new SimpleDateFormat(SHORT_DATE_FORMAT).parse(source);
                } else {
                    return new SimpleDateFormat(DATE_FORMAT).parse(source);
                }
            } catch (Exception e) {
                throw new RuntimeException(String.format("parser %s to date fail", source));
            }
        }
    }
}
